<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { uploadApp } from '$lib/api';
  import type { PlatformType } from '$lib/types';

  let file: File | null = null;
  let fileName = '';
  let fileSize = '';
  let platform: PlatformType = 'auto';
  let uploading = false;
  let errorMessage = '';
  let isDragging = false;

  // 支持的文件类型
  const allowedFileTypes = [
    '.exe', '.msi', '.msix', '.appx',  // Windows
    '.apk', '.aab',                    // Android
    '.ipa',                            // iOS
    '.app', '.dmg',                    // macOS
    '.deb', '.rpm', '.appimage',       // Linux
    '.hap',                            // Harmony OS
    '.zip'                             // 通用压缩包
  ];

  // 平台选项
  const platformOptions = [
    { value: 'auto', label: '自动检测' },
    { value: 'android', label: 'Android' },
    { value: 'ios', label: 'iOS' },
    { value: 'windows', label: 'Windows' },
    { value: 'macos', label: 'macOS' },
    { value: 'linux', label: 'Linux' },
    { value: 'harmony', label: 'HarmonyOS' }
  ];

  // 当选择文件时更新文件信息
  function handleFileSelect(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      setFile(input.files[0]);
    }
  }

  // 设置选中的文件
  function setFile(selectedFile: File) {
    file = selectedFile;
    fileName = selectedFile.name;
    fileSize = formatFileSize(selectedFile.size);
    errorMessage = '';
  }

  // 处理文件拖放
  function handleDragOver(event: DragEvent) {
    event.preventDefault();
    isDragging = true;
  }

  function handleDragLeave() {
    isDragging = false;
  }

  function handleDrop(event: DragEvent) {
    event.preventDefault();
    isDragging = false;
    
    if (event.dataTransfer?.files.length) {
      setFile(event.dataTransfer.files[0]);
    }
  }

  // 格式化文件大小显示
  function formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 上传文件
  async function submitForm() {
    if (!file) {
      errorMessage = '请选择一个文件进行上传';
      return;
    }

    try {
      uploading = true;
      errorMessage = '';
      
      const response = await uploadApp(file, platform);
      
      // 上传成功后跳转到任务状态页面
      goto(`/tasks/${response.task_id}`);
    } catch (error) {
      console.error('上传失败', error);
      errorMessage = error instanceof Error 
        ? error.message 
        : '上传失败，请稍后重试';
      uploading = false;
    }
  }
</script>

<div class="upload-container">
  <div 
    class="dropzone" 
    class:dragging={isDragging}
    on:dragover={handleDragOver}
    on:dragleave={handleDragLeave}
    on:drop={handleDrop}
  >
    <input 
      type="file" 
      id="file-upload" 
      accept={allowedFileTypes.join(',')}
      on:change={handleFileSelect} 
      disabled={uploading}
    />
    
    {#if file}
      <div class="file-info">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zm-1 2l5 5h-5V4zM6 20V4h5v7h7v9H6z"/>
        </svg>
        <div>
          <div class="file-name">{fileName}</div>
          <div class="file-size">{fileSize}</div>
        </div>
      </div>
    {:else}
      <label for="file-upload" class="upload-label">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
          <path d="M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/>
        </svg>
        <span>
          选择或拖放应用文件
          <small>支持 .apk, .ipa, .exe, .aab 等</small>
        </span>
      </label>
    {/if}
  </div>
  
  <div class="form-group">
    <label for="platform">平台类型:</label>
    <select 
      id="platform" 
      bind:value={platform} 
      disabled={uploading}
    >
      {#each platformOptions as option}
        <option value={option.value}>{option.label}</option>
      {/each}
    </select>
  </div>
  
  {#if errorMessage}
    <div class="error-message">
      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" fill="#e53935"/>
      </svg>
      {errorMessage}
    </div>
  {/if}
  
  <button 
    class="upload-button" 
    on:click={submitForm} 
    disabled={!file || uploading}
  >
    {#if uploading}
      <div class="spinner"></div>
      上传中...
    {:else}
      上传并分析
    {/if}
  </button>
</div>

<style>
  .upload-container {
    max-width: 600px;
    margin: 0 auto;
  }
  
  .dropzone {
    border: 2px dashed #ccc;
    border-radius: 8px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    margin-bottom: 1.5rem;
    transition: border-color 0.3s, background-color 0.3s;
  }
  
  .dropzone:hover, .dropzone.dragging {
    border-color: #4a90e2;
    background-color: rgba(74, 144, 226, 0.05);
  }
  
  .dropzone input[type="file"] {
    display: none;
  }
  
  .upload-label {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    color: #555;
  }
  
  .upload-label svg {
    margin-bottom: 1rem;
    fill: #777;
  }
  
  .upload-label span {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .upload-label small {
    margin-top: 0.5rem;
    color: #888;
    font-size: 0.8rem;
  }
  
  .file-info {
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    background-color: #f0f7ff;
  }
  
  .file-info svg {
    margin-right: 1rem;
    fill: #4a90e2;
  }
  
  .file-name {
    font-weight: bold;
    color: #333;
    word-break: break-all;
  }
  
  .file-size {
    font-size: 0.8rem;
    color: #777;
    margin-top: 0.25rem;
  }
  
  .form-group {
    margin-bottom: 1.5rem;
  }
  
  .form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: bold;
    color: #555;
  }
  
  select {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 1rem;
    background-color: white;
  }
  
  .error-message {
    background-color: #ffebee;
    color: #c62828;
    padding: 0.75rem;
    border-radius: 4px;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
  }
  
  .error-message svg {
    margin-right: 0.5rem;
    min-width: 20px;
  }
  
  .upload-button {
    width: 100%;
    padding: 0.75rem;
    background-color: #4a90e2;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: background-color 0.3s;
  }
  
  .upload-button:hover:not(:disabled) {
    background-color: #3a80d2;
  }
  
  .upload-button:disabled {
    background-color: #a0c3e8;
    cursor: not-allowed;
  }
  
  .spinner {
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-top: 2px solid white;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    margin-right: 0.5rem;
    animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style> 
